<?php
declare (strict_types = 1);

namespace app\controller;

use Exception;
use PHPMailer\PHPMailer\PHPMailer;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Session;
use think\Request;
use think\facade\Request as RequestFacade;
use app\validate\User as UserValidate;
use app\model\User as UserModel;//引进模型User改名为UserModel
class User
{
    protected  $middleware = [//控制器中间件
        \app\middleware\Auth::class 	=> ['except' 	=> ['index','create','read','save','confirm_email'] ],
        \app\middleware\Guest::class  => ['only' 		=> ['create'] ],
    ];

    public function index()
    {
        $users=UserModel::paginate(4);
        $count=$users->total();
        return view('user/index',compact('count','users'));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view();
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function  save(Request $request)
    {


        try {

            validate(UserValidate::class)->batch(true)->check($request->post());
            //halt($request->post());  //输出注册的数组
            $user=new UserModel();
            $user->name=$request->post('name');
            $user->email=$request->post('email');
            $user->password=sha1($request->post('password').getSalt());
            $user->is_admin=0;
            $user->save();

            $this->sendEmailConfirmationTo($user->active_token,$user->email);
            return redirect((string) url('home'))->with('success','恭喜您,注册成功,请前往邮箱激活账号~');

        } catch (ValidateException $e) {
            //记录旧的表单输入记录，闪存
            Session::flash('old',$request->post());
            if(!empty($errors=$e->getError()))
            {
                session('errors',$errors);//保存会话信息
                return redirect((string) url('User/create'));
            }


            // 验证失败
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if($member=UserModel::find($id))
        {
            $topics=$member->topics()->paginate(3);//每页显示六条
            $count=$topics->total();
            $loginuser=new UserModel();
            if(isLogin())
            {
                $userArr=loginUser();
                $loginuser=UserModel::find($userArr['id']);
            }

            return view('user/read',compact('topics','member','count','loginuser'));
        }
       else{
           return redirect((string) url('home'))->with('danger','用户不存在~');
       }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
        if(!isMineOpt($id))
        {
            return redirect((string) url('home'))->with('danger','非法访问~');
        }
        $User=UserModel::find($id);
        return view('user/edit',compact('User'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $user = UserModel::find($id);
        try {

            validate([
                'name|用户名称'=>'require|max:255|token|unique:user,name,'.$id,
                'password|密码'=>'min:6|confirm' ])->batch()->check($request->post());
            $user->name = $request->post('name');
            if($request->post('password')){
                $user->password=sha1($request->post('password').getSalt());
            }
            $user->save();
            session('user',null);
            if(Cookie::get('user_id')){
                Cookie::delete('user_id');
            }
            return redirect((string) url('login.create'))->with('success','恭喜您，修改成功,请重新登录~');

        } catch (ValidateException $e) {
            //记录旧的表单输入记录，闪存
            Session::flash('old',$request->post());
            if(!empty($errors=$e->getError()))
            {
                session('errors',$errors);//保存会话信息
                return redirect((string) url('User/edit',['id'=>$user->id]));
            }


            // 验证失败
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request,$id)
    {
        //token令牌验证，使用控制器里的验证方法
//         $check = $request->checkToken('__token__', $request->param());
//        if(false === $check) {
//        throw new ValidateException('invalid token');
//        }
        $user = UserModel::find($id);
        $name=$user->name;
        if(isLogin())
        {
            $login_user=loginUser();
        }
        if(isAdmin() && ($user->is_admin!=1) && ($login_user['id']!=$user->id))
        {
            $user->delete();
            return redirect((string) url('User/index'))->with('success','删除用户'.$name.'成功~');
        }
        else{
            abort(404,'非法操作~');
        }
    }

    public function followers($id)//关注我的
    {
        $user=UserModel::find($id);
        $users=$user->followers()->paginate(2);
        $count=$users->total();
        $title=$user->name.'的粉丝';
        return view('user/followers',compact('users','count','title'));
    }

    public function followings($id)//我关注的
    {
        $user=UserModel::find($id);
        $users=$user->followings()->paginate(2);
        $count=$users->total();
        $title=$user->name.'关注的用户';
        return view('user/followings',compact('users','count','title'));
    }

    public function confirm_email($token){//判断token与数据库的是否一致，一致则把active_token设置为null,actived设置为1.再次激活时因为邮箱还保持原来的token所以会查找为空集合
        $user = UserModel::where('active_token', $token)->findOrEmpty();

        if (!$user->isEmpty()) {
            $user->active_token=null;
            $user->actived=1;
            $user->save();
          $userArr=$user->toArray();
          $userArr['avatar']=$user->avatar;
          session('user',$userArr);
          return redirect((string) url('User/read',['id'=>$user->id]))->with('success','恭喜您,激活账号成功~');
        }
        else{
            return redirect((string) url('home'))->with('danger','激活账号失败~');
        }
    }


    protected function sendEmailConfirmationTo($token,$send_to_email){//发送邮件激活账号
        $mail = new PHPMailer(true);
        try {
     // 服务器设置
            $mail->isSMTP();
            $mail->Host = config('email.host'); // SMTP 服务器
            $mail->SMTPAuth = true;
            $mail->Username = config('email.username'); // SMTP 用户名
            $mail->Password = config('email.password'); // SMTP 密码
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 启用 TLS加密
            $mail->Port = 587; // TCP 端口

            // 收件人
            $mail->setFrom(config('email.username'), 'Mailer');
            $mail->addAddress($send_to_email); // 添加收件人

            //拼装url
            $url= RequestFacade::domain().url('confirm_email',['token'=>$token]);


            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '激活您的账户';
            $mail->Body = '请点击以下链接激活您的账户：<a href="'.$url.'">激活账户</a>';

            // 发送邮件
            $mail->send();

            } catch (Exception $e) {
                        return "邮件发送失败: {$mail->ErrorInfo}";
            }
    }
}
